package com.hxb.example.handler;

import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;

public class JobHandler {

    private static final Map<String, Function<String, String>> FUNCTION_MAP = new HashMap<>();
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(5);

    public static void addJob(ApplicationContext applicationContext, String jobName, String beanName, Method method) {
        FUNCTION_MAP.put(jobName, (params) -> {
            Object bean = applicationContext.getBean(beanName);
            EXECUTOR_SERVICE.submit(() -> {
                try {
                    method.invoke(bean, params);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            return "success";
        });
    }

    public static String execute(String jobName, String params) {
        return Optional.ofNullable(FUNCTION_MAP.get(jobName))
                .orElseThrow(() -> new RuntimeException("jobName not found"))
                .apply(params);
    }

}
